from flask import Blueprint, jsonify, request, send_file
import pandas as pd
import numpy as np
from pathlib import Path
import os
import sys
import traceback
from absence_analysis import main as analyze_data
import json

# 创建蓝图
absence_peixun_bp = Blueprint('absence-peixun', __name__, url_prefix='/absence-peixun')

def get_resource_path(relative_path):
    """获取资源文件的绝对路径，支持开发环境和打包环境"""
    if hasattr(sys, '_MEIPASS'):
        # PyInstaller 打包环境
        base_path = sys._MEIPASS
    else:
        # 开发环境
        base_path = os.path.dirname(os.path.abspath(__file__))
    
    return os.path.join(base_path, relative_path)

# 配置常量
DATA_DIR = Path("data")
OUTPUT_DIR = DATA_DIR / "alldata"
RESULT_FILE = OUTPUT_DIR / "外出培训未请假分析结果.xlsx"

def handle_nan_values(obj):
    """处理数据中的NaN值"""
    if isinstance(obj, (pd.Series, pd.DataFrame)):
        return obj.where(pd.notnull(obj), None)
    elif isinstance(obj, dict):
        return {k: handle_nan_values(v) for k, v in obj.items()}
    elif isinstance(obj, list):
        return [handle_nan_values(item) for item in obj]
    elif pd.isna(obj) or (isinstance(obj, float) and np.isnan(obj)):
        return None
    return obj

@absence_peixun_bp.route('/check-result-file', methods=['GET'])
def check_result_file():
    """检查结果文件是否存在"""
    try:
        exists = RESULT_FILE.exists()
        return jsonify({'exists': exists})
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@absence_peixun_bp.route('/generate-analysis', methods=['POST'])
def generate_analysis():
    """生成分析数据"""
    try:
        # 确保输出目录存在
        OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
        
        # 运行分析
        success = analyze_data()
        
        if success:
            return jsonify({'success': True})
        else:
            return jsonify({'success': False, 'error': '分析过程中出现错误'})
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@absence_peixun_bp.route('/get-data', methods=['POST'])
def get_data():
    """获取分析数据"""
    try:
        if not RESULT_FILE.exists():
            return jsonify({'error': '数据文件不存在'}), 404

        # 读取Excel文件
        df = pd.read_excel(RESULT_FILE)
        
        # 处理数据中的NaN值
        df = df.replace({np.nan: None})
        
        # 转换为字典列表并处理NaN值
        data = df.to_dict('records')
        data = handle_nan_values(data)
        
        # 获取所有列名
        all_columns = df.columns.tolist()

        return jsonify({
            'data': data,
            'all_columns': all_columns
        })

    except Exception as e:
        print(f"获取数据时出错: {str(e)}")
        traceback.print_exc()
        return jsonify({'error': str(e)}), 500

@absence_peixun_bp.route('/download-excel', methods=['POST'])
def download_excel():
    """下载Excel文件"""
    try:
        # 获取选定的字段和筛选后的数据
        selected_fields = request.form.getlist('fields')
        filtered_data = request.form.get('data')
        
        if not filtered_data:
            return jsonify({'error': '没有数据可供下载'}), 400
            
        # 将JSON字符串转换为Python对象
        filtered_data = json.loads(filtered_data)
        
        if not filtered_data:
            return jsonify({'error': '没有数据可供下载'}), 400
            
        # 创建DataFrame
        df = pd.DataFrame(filtered_data)
        
        if selected_fields:
            # 只保留选定的列
            df = df[selected_fields]

        # 创建临时文件名，使用时间戳确保唯一性
        from datetime import datetime
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        filename = f"外出培训未请假分析结果_{timestamp}.xlsx"
        
        # 创建临时目录用于存放下载文件
        temp_dir = Path(get_resource_path('temp'))
        temp_dir.mkdir(parents=True, exist_ok=True)
        temp_file = temp_dir / filename
        
        try:
            # 保存Excel文件
            df.to_excel(temp_file, index=False)
            
            response = send_file(
                temp_file,
                as_attachment=True,
                download_name=filename,
                mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            )
            
            # 设置回调以在发送后删除临时文件
            @response.call_on_close
            def cleanup():
                try:
                    if temp_file.exists():
                        temp_file.unlink()
                except Exception as e:
                    print(f"清理临时文件时出错: {str(e)}")
            
            return response
            
        except Exception as e:
            # 如果出错，确保清理临时文件
            if temp_file.exists():
                try:
                    temp_file.unlink()
                except:
                    pass
            return jsonify({
                'error': f'保存文件时出错: {str(e)}'
            }), 500

    except Exception as e:
        print(f"下载文件时出错: {str(e)}")
        traceback.print_exc()
        return jsonify({
            'error': f'下载文件时出错: {str(e)}'
        }), 500 